﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace SNRepairTools
{
    public static class IniHelper
    {

        public static string parameterSetting = LocateIniPath();

        private static string LocateIniPath()
        {
            List<string> foundPaths = new List<string>();
            string relativePath = @"Qmai\posServer\client\ParameterSetting.ini";

            foreach (var drive in DriveInfo.GetDrives())
            {
                if (drive.DriveType == DriveType.Fixed && drive.IsReady)
                {
                    string fullPath = Path.Combine(drive.RootDirectory.FullName, relativePath);
                    if (File.Exists(fullPath))
                    {
                        foundPaths.Add(fullPath);
                    }
                }
            }

            if (foundPaths.Count == 0)
            {
                Console.WriteLine("未找到任何 ParameterSetting.ini 文件！");
                return null;
            }
            else if (foundPaths.Count == 1)
            {
                Console.WriteLine($"已找到配置文件：{foundPaths[0]}");
                return foundPaths[0];
            }
            else
            {
                Console.WriteLine("找到多个配置文件，请选择一个：");
                for (int i = 0; i < foundPaths.Count; i++)
                {
                    Console.WriteLine($"{i + 1}. {foundPaths[i]}");
                }

                while (true)
                {
                    Console.Write("请输入要使用的配置文件编号：");
                    string input = Console.ReadLine();
                    if (int.TryParse(input, out int index) &&
                        index >= 1 && index <= foundPaths.Count)
                    {
                        return foundPaths[index - 1];
                    }
                    Console.WriteLine("输入无效，请重新输入编号。");
                }
            }
        }

        [DllImport("kernel32")] // 写入配置文件的接口
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")] // 读取配置文件的接口
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        // 向配置文件写入值
        public static void ProfileWriteValue(string section, string key, string value, string path)
        {
            WritePrivateProfileString(section, key, value, path);
        }

        // 读取配置文件的值
        public static string ProfileReadValue(string section, string key, string path)
        {
            StringBuilder sb = new StringBuilder(255);
            GetPrivateProfileString(section, key, string.Empty, sb, 255, path);
            return sb.ToString().Trim();
        }
    }
}
